<?php

namespace App\Models\Index;

use Illuminate\Database\Eloquent\Model;

class LiveAmuse extends Model
{
    public $table = 'live_amuse';
    public $timestamps = false;

    public function getCreatedTimeAttribute($val)
    {
        return date('Y-m-d',$val);
    }

    #根据分类id获取娱乐列表
    public static function getAmuseByCate(int $cate_id)
    {
        $data = self::query()->where('cate_id','=',$cate_id)->orderByDesc('click_count')->paginate(15)->toArray();
        if (empty($data)) {
            return [];
        } else {
            return $data;
        }
    }

    #获取每个分类下前三条的娱乐数据
    public static function getAmuseList()
    {
        $cate = LiveAmuseCate::getAmuseCateIds();
        if (empty($cate['data'])) {
            return $cate;
        }
        $cate_ids = $cate['data'];
        $count = count($cate_ids);
        $sql = self::with('cate')->where('cate_id','=',$cate_ids[0]['cate_id'])->orderBy('click_count','desc')->limit(3);
        for ($i = 1; $i <= $count; $i++) {
            $sql->unionAll(self::with('cate')->where('cate_id','=',$cate_ids[$i]['cate_id'])->orderBy('click_count','desc')->limit(3));
        }
        $data = $sql->get();
        if ($data->isEmpty()) {
            return $cate;
        } else {
            $newData = $data->sortBy('cate.sort')->groupBy('cate_id')->values()->all();
            $cate['data'] = $newData;
            return $cate;
        }
    }

    #根据分类ID获取娱乐列表
    public static function getAmuseListByCateId(int $cate_id)
    {
        $data = self::query()->where('cate_id','=',$cate_id)->orderBy('click_count','desc')->paginate(15)->toArray();
        if (empty($data)) {
            return [];
        } else {
            return $data;
        }
    }

    #关联娱乐表
    public function cate()
    {
        return $this->hasOne(LiveAmuseCate::class,'cate_id','cate_id');
    }


    #获取所有
    public static function getAmuseListAndPaginate()
    {
        $data = self::query()
                ->join('live_amuse_cate','live_amuse_cate.cate_id','=','live_amuse.cate_id')
                ->select('live_amuse.id','live_amuse.title','live_amuse.cate_id','live_amuse.img','live_amuse.url','live_amuse.click_count','live_amuse_cate.cate_name')
                ->orderByDesc('live_amuse.click_count')
                ->paginate(25);
        return $data;
    }

}
